<template>
  <div class="drag-table-container">
    <el-table :data="tableData" border fit highlight-current-row>
      <el-table-column label="ID" prop="id" width="50px"></el-table-column>
      <el-table-column label="Date" prop="date" width="150px"></el-table-column>
      <el-table-column label="Title" prop="title"></el-table-column>
      <el-table-column label="Author" prop="author" width="100px"></el-table-column>
      <el-table-column label="Importance" width="150px">
        <template slot-scope="scope">
          <i class="el-icon-star-on star" v-for="(item, index) in scope.row.importance" :key="index"></i>
        </template>
      </el-table-column>
      <el-table-column label="Readings" prop="readings" width="100px"></el-table-column>
      <el-table-column label="Status" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status !== 1" type="success" size="mini">published</el-tag>
          <el-tag v-else type="info" size="mini">draft</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Drag" width="70px">
        <template>
          <i class="el-icon-rank icon"></i>
        </template>
      </el-table-column>
    </el-table>
    <p>开始时的顺序：{{startValue}}</p>
    <p>调换后的顺序：[<span class="endValue"></span>]</p>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
export default {
  data() {
    return {
      startValue: [],
      endValue: [],
      tableData: this.$store.state.tableData
    }
  },
  mounted() {
    const el = document.querySelectorAll('.drag-table-container .el-table tbody')[0]
    this.startValue = this.tableData.map(c => c.id)
    Sortable.create(el, {
      ghostClass: 'sortable-ghost',
      onEnd: () => {
        const elChild = el.querySelectorAll('tr')
        for(let i = 0; i < elChild.length; i++) {
          this.endValue[i] = i !== elChild.length - 1 ? ' ' + elChild[i].querySelector('td').querySelector('.cell').innerHTML : ' ' + elChild[i].querySelector('td').querySelector('.cell').innerHTML + ' '
        }
        document.querySelector('.endValue').innerText = this.endValue
      }
    })
  }
}
</script>

<style scoped>
  .drag-table-container {
    user-select: none;
  }
  .star {
    font-size: 20px;
  }
  .icon {
    padding-left: 15px;
    font-size: 22px;
    font-weight: 600;
    cursor: pointer;
  }
</style>
